package com.groupbuying.redpacket.websocket;

import com.groupbuying.redpacket.timer.StandingListTimer;
import com.groupbuying.redpacket.utils.SpringConfigTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @ClassName StandingListWebSocket
 * @Description: TODO   排名情况WebSocket  （弃用）
 * @Author srlg3
 * @Date 2019/11/18
 * @Version V1.0
 **/
//@ServerEndpoint("/standingListWebSocket/{sid}")
//@Component
public class StandingListWebSocketServer {

    Logger logger = LoggerFactory.getLogger(StandingListWebSocketServer.class);

    //用于记录当前在线连接数
    private static int onlineCount = 0;

    //concurrent包的线程安全set，用来存放客户端对应的WebSocket对象
    private static CopyOnWriteArrayList<StandingListWebSocketServer> webSocketSet = new CopyOnWriteArrayList<>();

    //与某个客户端的连接会话，需要通过它来给客户发送数据
    private Session session;

    //接收sid
    private String sid = "";


    /**
     * 连接建立成功调用方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid){
        logger.info("已连接,任务id为：{}",sid);
        this.session = session;
        addOnlineCount();
        this.sid = sid;
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            logger.error("websocket IO异常");
        }
        StandingListTimer standingListTimer = SpringConfigTool.getBean(StandingListTimer.class);
        // 最后才执行定时任务
        standingListTimer.startTimer(this);
    }

    /**
     * 连接建立关闭调用的方法
     */
    @OnClose
    public void onClose(){
        StandingListTimer standingListTimer = SpringConfigTool.getBean(StandingListTimer.class);
        standingListTimer.colseTimer();

        webSocketSet.remove(this);
        subOnlineCount();
        logger.info("有一个连接关闭！当前在线人数为：{}",getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message,Session session){
        logger.info("收到sid：{},信息：{}",sid,message);
        //群发消息
        for (StandingListWebSocketServer webSocket:webSocketSet) {
            try {
                webSocket.sendMessage(message);
            } catch (Exception e) {
                logger.error("发送消息有误");
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session,Throwable error){
        logger.error("错误提示：webSocket发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(Object message) throws IOException {
        this.session.getBasicRemote().sendText(message.toString());
    }

    public static synchronized int getOnlineCount(){
        return onlineCount;
    }

    public static synchronized void addOnlineCount(){
        StandingListWebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount(){
        StandingListWebSocketServer.onlineCount--;
    }

    public String getSid() {
        return sid;
    }
}
